<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <!-- :value="activeName" -->
        <!-- @input="activeName = $event" -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="addRoleVisible = true">新增角色</el-button>

            <el-table
              :data="roleData"
              style="width: 100%; margin: 15px 0;"
              border
            >
              <!-- label: 列标题 -->
              <!-- prop: 指定该列渲染哪个数据字段 -->
              <el-table-column
                label="序号"
                type="index"
                width="80"
              />
              <el-table-column
                prop="name"
                label="角色名"
                sortable
              />
              <el-table-column
                prop="description"
                label="描述"
                sortable
              />
              <el-table-column
                label="操作"
              >
                <template slot-scope="{ row }">
                  <el-button type="text" @click="showSetRights(row.id)">分配权限</el-button>
                  <el-button type="text" @click="onEdit(row)">修改</el-button>
                  <el-button type="text" :disabled="isDisabled(point.roleDel)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              :current-page="queryData.page"
              :page-sizes="[2, 5, 10, 20]"
              :page-size="queryData.pagesize"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second">
            <!-- 开启栅格: 24 -->
            <el-row>
              <!-- 默认多少: 24 -->
              <el-col :offset="3" :span="8">
                <el-form ref="form" label-width="80px">
                  <el-form-item label="企业名称">
                    <el-input v-model="company.name" disabled />
                  </el-form-item>
                  <el-form-item label="公司地址">
                    <el-input v-model="company.companyAddress" disabled />
                  </el-form-item>
                  <el-form-item label="公司电话">
                    <el-input v-model="company.companyPhone" disabled />
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <el-input v-model="company.mailbox" disabled />
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input v-model="company.remarks" disabled />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 新增角色弹层 -->
    <el-dialog
      :title="roleDialogTitle"
      :visible.sync="addRoleVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form ref="addRoleForm" :model="addRoleForm" :rules="addRoleRules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addRoleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addRoleForm.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="defaultCheckedKeys = []"
    >
      <!-- data: 树形控件的数据 -->
      <!-- name child -->
      <!-- props: 修改默认渲染和子节点的字段 -->
      <el-tree
        ref="rightsTree"
        icon-class=" "
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :data="rightsData"
        node-key="id"
        :default-checked-keys="defaultCheckedKeys"
        check-strictly
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSaveRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCompanyInfo } from '@/api/company.js'
import {
  getRolesList,
  addRole,
  editRole,
  getRoleInfo,
  setRights
} from '@/api/roles.js'
import { getPermissions } from '@/api/permission.js'
import { transListToTree } from '@/utils'
import mixinsPoint from '@/mixins/point'
export default {
  name: 'Setting',

  mixins: [mixinsPoint],
  data() {
    return {
      activeName: 'first',
      company: {},
      // 角色表格数据
      roleData: [],
      queryData: {
        page: 1, // 页码
        pagesize: 2 // 每页的条数
      },
      total: 0,
      addRoleVisible: false,
      // 添加角色表单的数据
      addRoleForm: {
        name: '',
        description: ''
      },
      addRoleRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      setRightsDialogVisible: false,
      // 分配权限树形数据
      rightsData: [],
      defaultCheckedKeys: [],
      roleId: ''
    }
  },

  computed: {
    ...mapGetters(['companyId']),
    roleDialogTitle() {
      return this.addRoleForm.id ? '编辑角色' : '新增角色'
    }
  },

  created() {
    this.loadCompanyInfo()
    this.loadRolesList()
  },

  methods: {
    // 加载公司信息
    async loadCompanyInfo() {
      const res = await getCompanyInfo(this.companyId)
      this.company = res
    },
    // 加载角色列表
    async loadRolesList() {
      const res = await getRolesList(this.queryData)
      this.total = res.total
      this.roleData = res.rows
    },
    handleCurrentChange(val) {
      // 改变参数page
      this.queryData.page = val
      this.loadRolesList()
    },
    handleSizeChange(val) {
      this.queryData.pagesize = val
      this.loadRolesList()
    },
    addDialogClose() {
      // 重置表单/ 重置校验
      this.$refs.addRoleForm.resetFields()
      this.addRoleForm = {
        name: '',
        description: ''
      }
    },
    // 点击了确定
    async onSave() {
      try {
        await this.$refs.addRoleForm.validate()
        if (this.addRoleForm.id) {
          // 修改
          await editRole(this.addRoleForm)
          this.$message.success('更新成功')
        } else {
          await addRole(this.addRoleForm)
          this.$message.success('添加成功')
        }
        // console.log('表单校验成了')
        this.addRoleVisible = false
        this.loadRolesList()
      } catch (err) {
        console.log(err)
      }
    },
    // 点击了修改
    onEdit(row) {
      this.addRoleVisible = true
      // 根据row.id 发送请求获取最新数据
      this.addRoleForm = { ...row }
    },
    // 点击分配权限
    async showSetRights(id) {
      this.setRightsDialogVisible = true
      this.rightsData = transListToTree(await getPermissions(), '0')
      const res = await getRoleInfo(id)
      console.log(res.permIds)
      this.defaultCheckedKeys = res.permIds
      this.roleId = id
    },
    // 点击保存分配权限
    async onSaveRights() {
      const keys = this.$refs.rightsTree.getCheckedKeys()
      if (!keys.length) return this.$message.error('请选择必要的权限')
      // 发请求
      await setRights({ id: this.roleId, permIds: keys })
      this.$message.success('分配成功')
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .el-tabs__header {
  .el-tabs__item {
    width: 140px;
    text-align: center;
    font-size: 16px;
  }
}
</style>
